package SyncMap

import (
	"sync"
)

type SS struct {
	lock *sync.RWMutex
	data map[string]string
}

func NewSS() *SS {
	return &SS{
		lock: new(sync.RWMutex),
		data: make(map[string]string),
	}
}

//Get from maps return the k's value
func (m *SS) Get(k string) (val string, ok bool) {
	m.lock.RLock()
	defer m.lock.RUnlock()
	if val, ok = m.data[k]; ok {
		return
	}
	ok = false
	return
}

// Maps the given key and value. Returns false
// if the key is already in the map and changes nothing.
func (m *SS) Set(k string, v string) bool {
	m.lock.Lock()
	defer m.lock.Unlock()
	if val, ok := m.data[k]; !ok {
		m.data[k] = v
	} else if val != v {
		m.data[k] = v
	} else {
		return false
	}
	return true
}

// Returns true if k is exist in the map.
func (m *SS) Check(k string) bool {
	m.lock.RLock()
	defer m.lock.RUnlock()
	if _, ok := m.data[k]; !ok {
		return false
	}
	return true
}

func (m *SS) Delete(k string) {
	m.lock.Lock()
	defer m.lock.Unlock()
	delete(m.data, k)
}

func (m *SS) Items() map[string]string {
	m.lock.RLock()
	defer m.lock.RUnlock()
	return m.data
}
